﻿#ifndef CAMERAMANAGER_H
#define CAMERAMANAGER_H

#include "Utils/singleton.h"

#include "Infra/Vector.h"
#include "Infra/Function.h"
#include "GenICam/System.h"
#include "Include/GenICam/ErrorCode.h"
#include "Render.h"
#include <QMap>
#include <QObject>
#include <HalconCpp.h>

class CameraManager: public QObject, public Singleton<CameraManager>
{
   Q_OBJECT
public:
    typedef Dahua::Infra::TVector<Dahua::GenICam::ICameraPtr> CameraVec;
   // typedef void(*callback)(int w, int h, uint8_t *buffer, HWND hWnd);
	typedef void(*callback)(int w, int h, HalconCpp::HImage img, HWND hWnd);
   // typedef void(*disconnectCB)();
    /// 获取Interface信息
    struct CameraInfo
    {
        std::string name; // 树形结构的显示信息
		std::string sn;
        int         idx;  // 该idx为_cameraVec中Camera的序号
    };

    typedef QMap< std::string, std::vector<CameraInfo> > InterfaceMap;
	void SoftwareTrigger();
	bool SetCameraLive(bool bLive);
    BOOL Connect();
    BOOL Disconnect();

    // 开始拉流
    BOOL StartStreamGrabbing();
    BOOL StopStreamGrabbing();
    void GrabImage(callback, HWND wnd);
    InterfaceMap GetAllCameraInterfaces()
    {
        return _interfaces;
    }
    Dahua::GenICam::ICameraPtr GetCurrentCamera()
    {
        return _currentCamera;
    }
    void SelectCameraIndex(int index)
    {
        _currentCamera = _cameraVec[index];
    }
    BOOL IsConnected()
    {
        return _bRunning;
    }

    //save image
    void SaveImage(QString path);
	QString GetSerialNumWithInterfaceName(QString interfaceName);
	QString GetInterfaceNameWithSerialNum(QString sn);
	bool SelectCameraWithSerialNum(QString sn);
    void Init();
	HalconCpp::HImage GetLatestImage();
signals:
    void disconnectEvent();
    void connectedEvent(int state, int64_t w, int64_t h);

private:

    CameraManager();
    InterfaceMap _interfaces;
    // initilize tree view
    void initTree(CameraVec& cameraPtrVec);

	Dahua::Infra::CMutex				m_mxTime;
	int								    m_dDisplayInterval;         // 显示间隔
	uintmax_t							m_nFirstFrameTime;          // 第一帧的时间戳
	uintmax_t							m_nLastFrameTime;           // 上一帧的时间戳


	bool isTimeToDisplay();
	
    void onGetFrame(const Dahua::GenICam::CFrame & frame);
    void OnConnectEvent(const Dahua::GenICam::SConnectArg& arg);
    Dahua::GenICam::CSystem&    _systemIns;
    CameraVec                   _cameraVec;
    callback _cb;

    HWND _wnd;

    Dahua::GenICam::ICameraPtr          _currentCamera;   // 相机对象
    Dahua::GenICam::IStreamSourcePtr    _stream;          // 流对象
    bool								_isGrabbing;	  // 拉流标识
    bool								_bRunning;
    bool				m_bStopGrabbing;
    CRender                             _render;          // 显示对象
    FrameBufferSPtr _currentFrame;
	void UpdateDefaultCfg();
	bool m_bIsColorCamera;
	int64_t m_width;
	int64_t m_height;
protected:
    friend class Singleton<CameraManager>;
};

#endif // CAMERAMANAGER_H
